<template>
  <div>
    <!-- 面包屑指引 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 添加-->
    <el-button type="success" round @click="dialogFormsVisible = true"
      >添加</el-button
    >
    <!-- 渲染角色信息以及渲染角色权限(就是tag标签) -->
    <el-table :data="usersdata" style="width: 100%">
      <!-- 嵌套用户的权限，第一层循环 -->
      <!-- 下拉的箭头 -->
      <el-table-column type="expand">
        <!-- 插槽来访问子组件的值并保存使用 -->
        <template slot-scope="scope">
          <el-row
            class="diyi"
            v-for="(items, k) in scope.row.children"
            :key="k"
          >
            <!-- 分成6份，一共24份，一级标签占6份 -->
            <el-col :span="6">
              <el-tag closable @close="deletetag(scope.row, items.id)">{{
                items.authName
              }}</el-tag>
              <!-- 三角图标 -->
              <i class="el-icon-caret-right"></i>
            </el-col>
            <!-- 第二层循环嵌套 -->
            <el-col :span="18">
              <el-row
                class="dier"
                v-for="(v, key) in items.children"
                :key="key"
              >
                <!-- 第二层占8份 -->
                <el-col :span="8">
                  <el-tag
                    type="success"
                    closable
                    @close="deletetag(scope.row, v.id)"
                    >{{ v.authName }}</el-tag
                  >
                  <i class="el-icon-caret-right"></i>
                </el-col>
                <!-- 循环第三层，第三层占10份 -->
                <el-col :span="10">
                  <el-tag
                    type="warning"
                    v-for="(val, keys) in v.children"
                    :key="keys"
                    closable
                    @close="deletetag(scope.row, val.id)"
                    >{{ val.authName }}</el-tag
                  >
                </el-col>
              </el-row>
            </el-col>
          </el-row>
          <!-- 利用pre来改变循环的数据格式 -->
          <!-- <pre>{{ scope.row }}</pre> -->
        </template>
      </el-table-column>
      <!-- 渲染的表格 -->
      <el-table-column type="index"> </el-table-column>
      <el-table-column prop="roleName" label="角色名称"> </el-table-column>
      <el-table-column prop="roleDesc" label="角色描述"> </el-table-column>
      <el-table-column prop="address" label="操作">
        <!-- 查看用户信息 -->
        <template slot-scope="scope">
          <el-button
            icon="el-icon-search"
            circle
            size="mini"
            @click="editstar(scope.row)"
          ></el-button>
          <!-- 编辑用户信息 -->
          <el-button
            type="primary"
            icon="el-icon-edit"
            circle
            size="mini"
            @click="xiugai(scope.row)"
          ></el-button>
          <!-- 删除角色信息 -->
          <el-button
            type="danger"
            icon="el-icon-delete"
            circle
            size="mini"
            @click="outjuese(scope.row)"
          ></el-button>
          <!-- 角色授权 -->
          <el-button
            type="warning"
            round
            size="mini"
            @click="starshou(scope.row)"
          >
            <i class="el-icon-help"></i>
            角色授权
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 添加的弹出框 -->
    <el-dialog title="添加用户" :visible.sync="dialogFormsVisible">
      <el-form :model="addusers">
        <el-form-item label="角色名称">
          <el-input v-model="addusers.roleName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="addusers.roleDesc" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormsVisible = false">取 消</el-button>
        <el-button type="primary" @click="addsusers">确 定</el-button>
      </div>
      <!-- 自动刷新操作 -->
      <router-view v-if="isRouterAlive"></router-view>
    </el-dialog>

    <!-- 查找用户信息弹出框 -->
    <el-dialog title="查看用户" :visible.sync="dialogFormseideVisible">
      <el-form :model="edituserss">
        <el-form-item label="角色名称">
          <el-input
            v-model="edituserss.roleName"
            autocomplete="off"
            :disabled="true"
          ></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input
            v-model="edituserss.roleDesc"
            autocomplete="off"
            :disabled="true"
          ></el-input>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 编辑角色信息 -->
    <el-dialog title="编辑用户" :visible.sync="dialogxiugaiVisible">
      <el-form :model="bianjiusers">
        <el-form-item label="角色名称">
          <el-input
            v-model="bianjiusers.roleName"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input
            v-model="bianjiusers.roleDesc"
            autocomplete="off"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogxiugaiVisible = false">取 消</el-button>
        <el-button type="primary" @click="xiugaisusers">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 角色授权弹出框 -->
    <el-dialog title="角色授权" :visible.sync="dialogVisible" width="50%">
      <!-- 绑定角色权限的用户和树状信息，默认唯一的树节点，设置节点是否可选择， -->
      <el-tree
        :data="rightjuese"
        :props="treeusers"
        show-checkbox
        default-expand-all
        node-key="id"
        :default-checked-keys="defkeys"
        ref="treeusers"
      ></el-tree>
      <!-- 底部按钮区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="diao">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  //自动刷新操作，注册一个方法,之后调用
  provide() {
    return {
      reload: this.reload,
    };
  },

  data() {
    return {
      //自动刷新操作
      isRouterAlive: true,
      //渲染表格
      usersdata: [],
      //添加
      dialogFormsVisible: false, //关闭输入框
      addusers: {
        roleName: "",
        roleDesc: "",
      },
      //和获取角色信息
      dialogFormseideVisible: false,
      edituserss: {},
      // 编辑用户角色
      dialogxiugaiVisible: false,
      bianjiusers: {},
      //角色授权
      // 获取所有权限角色
      rightjuese: {},
      dialogVisible: false,
      //树状信息展示绑定对象
      treeusers: {
        label: "authName", //树状权限角色的每个属性值
        children: "children", //这个是绑定子树状信息(实现嵌套)
      },
      //树状角色信息展示
      defkeys: [],
      //将获取当前节点的id保存
      roleID: "",
    };
  },
  methods: {
    // 自动刷新页面的方法
    roload() {
      this.isRouterAlive = false;
      this.$nextTick(function () {
        this.isRouterAlive = true;
      });
    },

    // 修改角色授权，点击确定为角色授权
    async diao() {
      // 获取选中节点(全选)和半选中节点(没有被全选的单个的)key(就是数组所储存的id)
      // getCheckedKeys，若节点可被选择（即 show-checkbox 为 true），则返回目前被选中的节点的 key 所组成的数组---全选的(key)id
      // getHalfCheckedKeys 若节点可被选择（即 show-checkbox 为 true），则返回目前半选中的节点的 key 所组成的数组---没有被全选的id
      //利用一个数组来储存他
      const keys = [
        ...this.$refs.treeusers.getCheckedKeys(), //refs来操作dom,这个是全选的key(id)用扩展用算符结构出来每一个
        ...this.$refs.treeusers.getHalfCheckedKeys(), //refs来操作dom,这个是半选的key(id)用扩展用算符结构出来每一个
      ];
      //用逗号把全选和半选的分割之后装换位字符串发送给后端，就是每个权限的id
      const arr = keys.join(",");
      //发起请求，将角色id和权限ID发送给后端，操作之后更新数据库，给每个角色授权
      let { data } = await this.$req.post(`roles/${this.roleID}/rights`, {
        rids: arr
      });
      //分配权限失败
      if (data.meta.status !== 200) {
        this.$message.error(data.meta.msg);
        //分配权限成功
      } else {
        this.$message({
          type: "success",
          message: data.meta.msg,
        });
        // 关闭弹窗
        this.dialogVisible = false;
      }
    },


    // 点击删除tag标签,根据权限角色id和权限id(删除角色指定权限),有错误弹窗提醒用户信息不对，
    deletetag(role, rightId) {
      //弹窗提醒用户确定删除
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }) //操作成功执行
        .then(async () => {
          //发起请求，向服务器发送role的id和rightsId，请求服务器数据
          let { data } = await this.$req.delete(
            `/role/${role.id}/rights/${rightId}`
          ); //状态为200说明成功，把数据赋值给role的子标签，弹出弹框提醒用户
          if (data.meta.status == 200) {
            this.$message({
              type: "success",
              message: data.meta.msg,
            });
            role.children = data.data;
          } else {
            this.$message.error(data.meta.msg);
          }
        });
    },

    // 获取全部角色权限
    async starshou(rows) {
      //利用插槽获取角色的id并保存，就是当前角色的信息
      this.roleID = rows.id;
      console.log(this.roleID);
      //获取树状的角色权限
      let { data } = await this.$req.get("/rights/tree");
      console.log(data);
      //判断成功将数据赋值给rightjuese，并让弹出框显示
      if (data.meta.status == 200) {
        this.$message({
          type: "success",
          message: data.meta.msg,
        });
        this.rightjuese = data.data;
        // 定义一个空数组来存储循环之后角色的id
        var keys = [];
        //循环角色的值，给新的数组。
        rows.children.forEach((item) => {
          item.children.forEach((index) => {
            index.children.forEach((val) => {
              keys.push(rows,val.id);
            });
          });
        });
        //将循环出来的id传给新数组
        this.defkeys = keys;
        //将弹框打开
        this.dialogVisible = true;
      } else {
        //判断失败，就弹出弹框提醒用户
        this.$message.error(data.meta.msg);
      }
    },

    // 删除用户
    outjuese(userinfo) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(async () => {
        let { data } = await this.$req.delete("/roles/" + userinfo.id);
        if (data.meta.status == 200) {
          this.$message({
            type: "success",
            message: data.meta.msg,
          });
          //调用自动刷新方法
          this.roload();
        } else {
          this.$message.error(data.meta.msg);
        }
      });
    },

    // 点击确定编辑用户信息
    async xiugaisusers() {
      // 根据id来修改角色信息
      let { data } = await this.$req.put(
        "/roles/" + this.bianjiusers.id,
        this.bianjiusers
      );
      if (data.meta.status == 200) {
        this.$message({
          message: data.meta.msg,
          type: "success",
        });
        //请求数据成功之后，将弹出框关闭
        this.dialogxiugaiVisible = false;
      } else {
        this.$message.error(data.meta.msg);
      }
    },

    //编辑用户获取用户信息
    xiugai(userinfo) {
      this.dialogxiugaiVisible = true;
      this.bianjiusers = userinfo;
    },

    //根据用户id查询用户详情信息
    editstar(userinfo) {
      this.dialogFormseideVisible = true;
      this.edituserss = userinfo;
    },

    //添加
    async addsusers() {
      let { data } = await this.$req.post("/roles", this.addusers);
      if (data.meta.status == 201) {
        //添加成功弹出框
        this.$message({
          message: data.meta.msg,
          type: "success",
        });
        //点击确定关闭弹窗
        this.dialogFormsVisible = false;
        //调用自动刷新
        this.roload();
      } else {
        this.$message.error(data.meta.msg);
      }
    },
  },
  //页面加载获取数据
  async mounted() {
    let { data } = await this.$req.get("/roles");
    console.log(data);
    if (data.meta.status == 200) {
      this.$message({
        message: data.meta.msg,
        type: "success",
      });
      this.usersdata = data.data;
    } else {
      this.$message.error(data.meta.msg);
    }
  },
};
</script>

<style>
el-tag {
  margin-top: 0px;
}
.el-col {
  line-height: 10px;
}
.diyi {
  border-top: 1px solid yellow;
  border-bottom: 1px solid yellow;
}
.dier {
  border-top: 1px solid pink;
}
</style>